﻿$(document).ready(function () {
    //$('#createEventBooking_chosen span').html("Select a Event...");
    //$('#createEventBooking').val("");
    //$('#createTotalBook').val("");
    if ($('#table_Page').length) {
        var oTable = $('#table_Page').dataTable({
            "sDom": "<'dt-top-row'Tlf>r<'dt-wrapper't><'dt-row dt-bottom-row'<'row-fluid'ip>",
            "oTableTools": {
                "aButtons": [
                    "copy",
                    "print",
                    {
                        "sExtends": "collection",
                        "sButtonText": 'Save <span class="caret" />',
                        "aButtons": ["csv", "xls", "pdf"]
                    }
                ],
                "sSwfPath": "~/../../../Content/Admin/js/lib/datatables/extras/TableTools/media/swf/copy_csv_xls_pdf.swf"
            },
            "fnInitComplete": function(oSettings, json) {
                $(this).closest('#table_Page_wrapper').find('.DTTT.btn-group').addClass('table_tools_group').children('a.btn').each(function() {
                    $(this).addClass('btn-mini btn-inverse');
                });
            },
            "bServerSide": true,
            "sAjaxSource": "~/../LoadPageResult",
            "bProcessing": true,
            /*"sPaginationType": "full_numbers",*/
            "aoColumns": [
                {
                    "sName": "Title",
                    "mDataProp": "Title",
                    "bSortable": true,
                },
                {
                    "sName": "Alias",
                    "mDataProp": "Url",
                    "bSortable": true,
                },
                {
                    "sName": "Actions",
                    "mDataProp": "PageId",
                    "bSortable": false,
                    "fnRender": function(oObj) {
                        return '<ul class="ico-list">' +
                            '<li><a href="Edit/' + oObj.aData["PageId"] + '" title="Edit Page"><i class="fa icon-edit"></i></a> </li>' +
                            '<li><a href="#DeletePage" data-toggle="modal" title="Delete Page" id="btnDeletePage" onclick="getIdPage(' +
                            oObj.aData["PageId"] + ')"><i class="fa icon-remove"></i> </a></li>' +
                            '</ul>';
                    }
                },
            ],
        });
    }
})

$('#txtTitlePage').blur(function () {
    var url = $.trim($(this).val());
    if (url == "") {
        $("#dvTitlePage").closest("div").addClass("f-error");
        $("#txtTitleRequired").remove();
        $("#dvTitlePage").closest("div").append('<label class="error" id="txtTitleRequired" generated="true">This field is required.</label>');
        $("#btnCreatePage").attr("disabled", "disabled");
    } else {
        $("#dvTitlePage").closest("div").removeClass("f-error");
        $("#txtTitleRequired").remove();
        $("#btnCreatePage").removeAttr("disabled");
        url = make_friendly_link(url);
        url = url.toLowerCase();
        $("#txtURLPage").val(url);

        // check the title of page was created

        var nameEvent = $('#txtTitlePage').val();
        var data = { name: nameEvent, id: 0 }
        $.ajax(
            {
                type: "Post",
                url: "CheckExitNamePage",
                data: data,
                dataType: "JSON",
                success: function(result) { //Ham success xu li
                    if (result) {
                        $("#dvTitlePage").closest("div").addClass("f-error");
                        $("#txtTitleUsed").remove();
                        $("#dvTitlePage").closest("div").append('<label class="error" id="txtTitleUsed" generated="true">The title of page is used.</label>');
                        $("#btnCreatePage").attr("disabled", "disabled");
                    } else {
                        $("#dvTitlePage").closest("div").removeClass("f-error");
                        $("#txtTitleUsed").remove();
                        $("#btnCreatePage").removeAttr("disabled");
                    }
                    // chua can kiem tra nhung sau nay phai implement
                    //checkURLPage();
                },
            });
    }
})


$('#txtTitlePageEdit').blur(function() {
    var idP = 0;
    var url = $.trim($(this).val());
    if (url == "") {
        $("#dvTitlePage").closest("div").addClass("f-error");
        $("#txtTitleRequired").remove();
        $("#dvTitlePage").closest("div").append('<label class="error" id="txtTitleRequired" generated="true">This field is required.</label>');
        $("#btnCreatePage").attr("disabled", "disabled");
    } else {
        $("#dvTitlePage").closest("div").removeClass("f-error");
        $("#txtTitleRequired").remove();
        $("#btnCreatePage").removeAttr("disabled");
        url = make_friendly_link(url);
        url = url.toLowerCase();
        $("#txtURLPageEdit").val(url);

        // check the title of page was created
        idP = $("#idPage").val();
        var nameEvent = $('#txtTitlePageEdit').val();
        var data =
        {
            name: nameEvent,
            id:idP
        }
    $.ajax(
        {
            type: "Post",
            url: "../CheckExitNamePage/",
            data: data,
                dataType: "JSON",
                success: function (result) {
 //Ham su cess xu li
                    if (result) {
                        $("#dvTitlePage").closest("div").addClass("f-error");
                        $("#txtTitleUsed").remove();
                        $("#dvTitlePage").closest("div").append('<label class="error" id="txtTitleUsed" generated="true">The title of page is used.</label>');
                        $("#btnCreatePage").attr("disabled", "disabled");
                    } else {
                        $("#dvTitlePage").closest("div").removeClass("f-error");
                        $("#txtTitleUsed").remove();
                        $("#btnCreatePage").removeAttr("disabled");
                    }
                    // chua can kiem tra nhung sau nay phai implement
                    //checkURLPage();
                },
            });
    }
})

$("#confirmDeletePage").on('click', function () {
    var data = {
        id: $("#hiddenPageId").val()
    }
    $.ajax(
        {
            type: "Post",
            url: "DeletePage",
            data: data,
            dataType: "JSON",
            success: function (result) {//Ham success xu li
                if (result == true) {
                    RefreshTable("#table_Page", "LoadPageResult");
                    $.sticky("Delete Page is successfull.", { autoclose: 3000, position: "top-right", type: "st-success" });
                } else {
                    $.sticky("Delete Page is unsuccessfull.", { autoclose: 3000, position: "top-right", type: "st-error" });
                }
                $('#DeletePage').modal('hide');
            },

        });
})

function RefreshTable(tableId, urlData) {
    $.getJSON(urlData, null, function (json) {
        table = $(tableId).dataTable();
        oSettings = table.fnSettings();

        table.fnClearTable(this);

        for (var i = 0; i < json.aaData.length; i++) {
            table.oApi._fnAddData(oSettings, json.aaData[i]);
        }

        oSettings.aiDisplay = oSettings.aiDisplayMaster.slice();
        table.fnDraw();
    });
}

function make_friendly_link(s) {
    if (typeof s == "undefined") {
        return;
    }
    var i = 0, uni1, arr1;
    var newclean = s;
    uni1 = 'à|á|ạ|ả|ã|â|ầ|ấ|ậ|ẩ|ẫ|ă|ằ|ắ|ặ|ẳ|ẵ|À|Á|Ạ|Ả|Ã|Â|Ầ|Ấ|Ậ|Ẩ|Ẫ|Ă|Ằ|Ắ|Ặ|Ẳ|Ẵ|A';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'a');

    uni1 = 'è|é|ẹ|ẻ|ẽ|ê|ề|ế|ệ|ể|ễ|È|É|Ẹ|Ẻ|Ẽ|Ê|Ề|Ế|Ệ|Ể|Ễ|E';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'e');

    uni1 = 'ì|í|ị|ỉ|ĩ|Ì|Í|Ị|Ỉ|Ĩ|I';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'i');

    uni1 = 'ò|ó|ọ|ỏ|õ|ô|ồ|ố|ộ|ổ|ỗ|ơ|ờ|ớ|ợ|ở|ỡ|Ò|Ó|Ọ|Ỏ|Õ|Ô|Ồ|Ố|Ộ|Ổ|Ỗ|Ơ|Ờ|Ớ|Ợ|Ở|Ỡ|O';
    arr1 = uni1.split('|');
    for (i = 0; i < arr1.length; i++) newclean = replaceall(newclean, arr1[i], 'o');

    uni1 = 'ù|ú|ụ|ủ|ũ|ư|ừ|ứ|ự|ử|ữ|Ù|Ú|Ụ|Ủ|Ũ|Ư|Ừ|Ứ|Ự|Ử|Ữ|U';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'u');

    uni1 = 'ỳ|ý|ỵ|ỷ|ỹ|Ỳ|Ý|Ỵ|Ỷ|Ỹ|Y';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'y');

    uni1 = 'd|Đ|D';
    arr1 = uni1.split('|');
    for (i = 0; i < uni1.length; i++) newclean = replaceall(newclean, arr1[i], 'd');

    newclean = newclean.toLowerCase();

    ret = newclean.replace(/[\&]/g, '-and-').replace(/[^a-zA-Z0-9._-]/g, '-').replace(/[-]+/g, '-').replace(/-$/, '');

    return ret;
}

function replaceall(str, replace, with_this) {
    var str_hasil = "";
    var temp;

    for (var i = 0; i < str.length; i++) {
        if (str[i] == replace) {
            temp = with_this;
        } else {
            temp = str[i];
        }

        str_hasil += temp;
    }

    return str_hasil;
}